package com.wangfugui.mybatisplus.service;

import com.aliyun.oss.*;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.*;
import com.wangfugui.mybatisplus.config.ObsConfig;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Slf4j
public class OssService {
    @Autowired
    private ObsConfig obsConfig;

    private OSS ossClient;

    @PostConstruct
    public void init() {
//        ossClient = new OSSClient(ObsConfig.BUCKET_NAME1,ObsConfig.ACCESS_KEY_ID,ObsConfig.ACCESS_KEY_SECRET);
//        ossClient = new OSSClientBuilder().build(
//                obsConfig.getEndpoint(),
//                obsConfig.getAccessKeyId(),
//                obsConfig.getAccessKeySecret());
    }

    @PreDestroy
    public void destroy() {
        if (ossClient != null) {
            ossClient.shutdown();
        }
    }

    /**
     * 上传文件
     */
//    public String upload(InputStream inputStream, String fileName) {
//        try {
//            // 创建PutObject请求
//            ossClient.putObject(ossConfig.getBucketName(), fileName, inputStream);
//            //设置权限 这里是公开读
//            ossClient.setBucketAcl(ossConfig.getBucketName(), CannedAccessControlList.PublicRead);
//            return generateUrl(fileName);
//        } catch (Exception e) {
//            throw new RuntimeException("文件上传失败", e);
//        }
//    }
    public static String upload(InputStream file,String fileName){
        String endpoint=ObsConfig.END_POINT;
        String accessKeyId=ObsConfig.ACCESS_KEY_ID;
        String accessKeySecret=ObsConfig.ACCESS_KEY_SECRET;
        String bucketName=ObsConfig.BUCKET_NAME1;
        String fileHost=ObsConfig.FILE_HOST;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = format.format(new Date());
        if(null == file){
            return null;
        }

        OSSClient ossClient = new OSSClient(endpoint,accessKeyId,accessKeySecret);
        try {
            //容器不存在，就创建
            if(! ossClient.doesBucketExist(bucketName)){
                ossClient.createBucket(bucketName);
                CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
                createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                ossClient.createBucket(createBucketRequest);
            }
            //创建文件路径
            String fileUrl = fileHost+"/"+(dateStr + "/" + UUID.randomUUID().toString().replace("-","")+"-"+fileName);
            //上传文件
            PutObjectResult result = ossClient.putObject(new PutObjectRequest(bucketName, fileUrl, file));
            //设置权限 这里是公开读
            ossClient.setBucketAcl(bucketName,CannedAccessControlList.PublicRead);
            if(null != result){
                log.info("==========>OSS文件上传成功,OSS地址："+fileUrl);
                log.info("==========>OSS文件上传成功,OSS地址："+result.toString());

                return fileUrl;
            }
        }catch (OSSException oe){
            log.error(oe.getMessage());
        }catch (ClientException ce){
            log.error(ce.getMessage());
        }finally {
            //关闭
            ossClient.shutdown();
        }
        return null;
    }

    public static String upload(File file){
        log.info("=========>OSS文件上传开始："+file.getName());
        String endpoint=ObsConfig.END_POINT;
        String accessKeyId=ObsConfig.ACCESS_KEY_ID;
        String accessKeySecret=ObsConfig.ACCESS_KEY_SECRET;
        String bucketName=ObsConfig.BUCKET_NAME1;
        String fileHost=ObsConfig.FILE_HOST;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = format.format(new Date());
        if(null == file){
            return null;
        }

        OSSClient ossClient = new OSSClient(endpoint,accessKeyId,accessKeySecret);
        try {
            //容器不存在，就创建
            if(! ossClient.doesBucketExist(bucketName)){
                ossClient.createBucket(bucketName);
                CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
                createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                ossClient.createBucket(createBucketRequest);
            }
            //创建文件路径
            String fileUrl = fileHost+"/"+(dateStr + "/" + UUID.randomUUID().toString().replace("-","")+"-"+file.getName());
            //上传文件
            PutObjectResult result = ossClient.putObject(new PutObjectRequest(bucketName, fileUrl, file));
            //设置权限 这里是公开读
            ossClient.setBucketAcl(bucketName,CannedAccessControlList.PublicRead);
            if(null != result){
                log.info("==========>OSS文件上传成功,OSS地址："+fileUrl);
                log.info("==========>OSS文件上传成功,OSS地址："+result.toString());

                return fileUrl;
            }
        }catch (OSSException oe){
            log.error(oe.getMessage());
        }catch (ClientException ce){
            log.error(ce.getMessage());
        }finally {
            //关闭
            ossClient.shutdown();
        }
        return null;
    }


//    /**
//     * 生成文件访问URL（带签名）
//     */
//    public String generateUrl(String fileName) {
//        Date expiration = new Date(System.currentTimeMillis() + ossConfig.getUrlExpireTime() * 1000);
//        URL url = ossClient.generatePresignedUrl(ossConfig.getBucketName(), fileName, expiration);
//        return url.toString();
//    }
//
//    /**
//     * 删除文件
//     */
//    public void delete(String fileName) {
//        ossClient.deleteObject(ossConfig.getBucketName(), fileName);
//    }
//
//    /**
//     * 获取上传策略（前端直传用）
//     */
//    public Map<String, String> getUploadPolicy(String dir) {
//        long expireTime = System.currentTimeMillis() + ossConfig.getUrlExpireTime() * 1000;
//        Date expiration = new Date(expireTime);
//        PolicyConditions policyConds = new PolicyConditions();
//        policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE,
//                0, ossConfig.getMaxSize());
//        policyConds.addConditionItem(PolicyConditions.COND_KEY, dir + "${filename}");
//
//        String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
//        String encodedPolicy = BinaryUtil.toBase64String(postPolicy.getBytes());
//        String postSignature = ossClient.calculatePostSignature(postPolicy);
//
//        Map<String, String> respMap = new LinkedHashMap<>();
//        respMap.put("accessid", ossConfig.getAccessKeyId());
//        respMap.put("policy", encodedPolicy);
//        respMap.put("signature", postSignature);
//        respMap.put("dir", dir);
//        respMap.put("host", "https://" + ossConfig.getBucketName() + "." + ossConfig.getEndpoint());
//        respMap.put("expire", String.valueOf(expireTime / 1000));
//        return respMap;
//    }
}
